<template>
<div>
    <h2>新闻列表</h2>
    <div>
        <news-list :list="newsList" :currentPage="currentPage" @page="getNewsList" />

        <el-table :data="newsList" size="small" stripe>
            <el-table-column prop="title" label="标题" width="300">
            </el-table-column>
            <el-table-column prop="path" label="链接" width="400"> </el-table-column>
           <el-table-column label="操作">
               <template slot-scope="scope">
                   <el-button type="text" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                   <el-button type="text" size="small">删除</el-button>
               </template>
           </el-table-column>
        </el-table>
        <el-dialog title="编辑" :visible.sync="editDialogVisible" top="5vh" width="90%">
           <news-form :data="formData" @news-submit="updateNews"/>
        </el-dialog>
    </div>
</div>
</template>

<script>
import NewsList from "../../components/news/List";
import baseMixin from '../../store/app-mixin';
import NewsForm from './NewsForm';
import {
    createNamespacedHelpers
} from "vuex";

const {
    mapState,
    mapActions,
    //在src/store/index.js文件中指定了名为news的子状态模块，news子状态中也指定了namespaced为true,那么就需要通过createNamespacedHelpers方法告诉mapState和mapActions方法，映射时要默认指名news命名空间
} = createNamespacedHelpers("news");

export default {
    //如果有多个组件共用的方法，将它们写在单独的文件中，用mixins结构进行混入，参见src/store/app-mixin.js
    mixins: [baseMixin],
    data(){
        return {
            editDialogVisible:false,
            formData:null,
            currentIndex:0
        };
    },
    computed: {
        //在src/store/modules/news.js中定义了newsList和currentPage状态，使用vuex提供的mapState方法将它们映射到此处，实际上是为组件也定义了一个同步的计算属性并把store中的状态做了包装
        ...mapState(["newsList", "currentPage"]),
    },
    methods: {
        handleEdit(index){
            this.editDialogVisible = true;
            this.formData = {...this.newsList[index]};
            this.currentIndex = index;
        },
        //在src/store/modules/news.js中定义了getNewsList方法，使用vuex提供的mapActions方法将它映射到此处，实际上是为当前组件也定义了一个同名方法并把store中的方法做了包装
        ...mapActions(["getNewsList"]),
        updateNews(){
            this.$store.commit('news/updateNews', {index:this.currentIndex, newData:this.formData});
            this.editDialogVisible = false;
        }
    },
    components: {
        //子组件，参见src/components/NewsList.js
        NewsList, NewsForm
    },
    mounted() {
        //当组件加载后调用getNewsList取新闻数据
        this.getNewsList({
            page: 1,
            count: 10
        });
    },
};
</script>
